package lock.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import redis.clients.jedis.params.SetParams;

/**
 * @author 徒有琴
 */
public class Buyer {
    Jedis jedis = new Jedis("www.hf1901.com", 6379);

    public boolean lock(String threadName) {//抢锁
        String lock = jedis.set("lock", threadName, SetParams.setParams().nx().ex(5));
        if ("OK".equals(lock)) {
            jedis.watch("lock");
            return true;
        }
        return false;
    }

    public int getAmount() {
        return Integer.parseInt(jedis.get("amount"));
    }

    public void updateAmount(int amount, int num) {
        Transaction trans = jedis.multi();
        //jedis.decrBy("amount", num);
        trans.decrBy("amount", num);
        trans.exec();
        jedis.unwatch();




        jedis.del("lock");
    }

    public void close() {
        jedis.close();
    }
}
